import React, { Component } from 'react';
import {
  View,Text,StyleSheet,ScrollView,TextInput,Modal,DeviceEventEmitter,
    Platform
} from 'react-native';
import pxToDp from '../common/comm';
import * as DATA from '../data/data';
import * as COMM from '../common/comm';

export default class ApplyTixian extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      money:0,
      tixian:'',
      isModal:false,
        loginkey:this.props.navigation.state.params.userInfo.loginkey||null,
    };
  }

  //提示框3秒后消失
  _show(txt) {
    this.setState({
      isModal: true,
      alertTxt: txt
    });
    this.timer = setTimeout(() => {this._hide()},2000);
  }

  _hide() {
    this.setState({
      isModal:false
    })
  }

  static navigationOptions={
    headerTintColor:'#fff',
    headerTitle: '申请提现',
    headerStyle: {
      backgroundColor: DATA.BASE_COLOR,
        height:Platform.OS === 'android'?pxToDp(84):pxToDp(110)
    },
    headerTitleStyle: {
      color: '#fff',
      fontSize: pxToDp(34),
        marginLeft:Platform.OS === 'android'?pxToDp(185):null
    },
    gesturesEnabled :true
  }

  check(){
    //申请提现
    if (this.state.tixian == '') {
      this._show('请输入提现金额!');
      return false;
    }
    if (this.state.tixian < 5) {
      this._show('提现金额不低于5元!');
      return false;
    }
    if (isNaN(this.state.tixian)) {
      this._show('请输入数字!');
      return false;
    }
    if (Number(this.state.money) < Number(this.state.tixian)) {
      this._show('提现金额不能大于当前账户余额!');
      return false;
    }
    return true;
  }

  componentWillMount() {
    let _that = this;
    let data2 = 'loginkey=' + this.state.loginkey;
    fetch(DATA.USERINFO_URL, {
      method: "POST",
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: data2
    })
        .then((response) => {       // 数据解析方式
          if (response.ok) {
            return response.json();
          }
        })
        .then((responseData) => {       // 获取到的数据处理
          _that.setState({
            money:responseData.info.account
          })
        })
        .catch((error) => { // 错误处理
          //_that._show('获取数据失败，请重试！');
        })
        .done();
  }

  all(){
    this.setState({
      tixian:this.state.money
    })
  }

  componentWillMount(){
      let _that = this;
      let data2 = 'loginkey=' + this.state.loginkey;
      fetch(DATA.USERINFO_URL, {
          method: "POST",
          headers: {'Content-Type': 'application/x-www-form-urlencoded'},
          body: data2
      })
          .then((response) => {       // 数据解析方式
              if (response.ok) {
                  return response.json();
              }
          })
          .then((responseData) => {       // 获取到的数据处理
              if(responseData.status == 1){
                  _that.setState({
                      money:responseData.info.account
                  })
              }
          })
          .catch((error) => { // 错误处理
              //_that._show('获取数据失败，请重试！');
          })
          .done();
  }

  _onPress(){
    let isCheck = this.check();
    let _that = this;
    if(isCheck){
      let data2 = 'loginkey='+this.state.loginkey+'&money='+this.state.tixian;
      fetch(DATA.SAVETIXIAN_URL, {
        method: "POST",
        headers:{'Content-Type': 'application/x-www-form-urlencoded' },
        body: data2
      })
          .then((response) => {       // 数据解析方式
            if (response.ok) {
              return response.json();
            }
          })
          .then((responseData) => {       // 获取到的数据处理
            _that._show(responseData.msg);
              if(responseData.status == 1){
                  let now = COMM.toDecimal2(COMM.toDecimal2(this.state.money)-COMM.toDecimal2(this.state.tixian))
                  _that.setState({
                      money:now,
                      tixian:''
                  })
                  DeviceEventEmitter.emit('changeAccount',now);
              }
          })
          .catch((error) => { // 错误处理
            _that._show(error);
          })
          .done();
    }
  }

  render() {
    return (
      <ScrollView
        contentContainerStyle={styles.contentContainer}
      >
        <Modal
            animationType='fade'            // 淡入淡出
            transparent={true}              // 透明
            visible={this.state.isModal}    // 根据isModal决定是否显示
            onRequestClose={() => {this.onRequestClose()}}  // android必须实现
            >
          <View style={modalStyle.modalViewStyle}>
            <View style={modalStyle.hudViewStyle}>
              <Text style={modalStyle.hudTextStyle}>{this.state.alertTxt}</Text>
            </View>
          </View>
        </Modal>
        <View>
          <View style={styles.row}>
            <Text style={[styles.title,{marginLeft:pxToDp(25)}]}>余额：</Text>
            <Text style={styles.input}>{this.state.money}</Text>
            <Text
                style={styles.all}
                onPress={this.all.bind(this)}>全部提现</Text>
          </View>
          <View style={styles.row}>
            <Text style={[styles.title,{marginLeft:pxToDp(25)}]}>请输入金额(元)：</Text>
            <TextInput keyboardType='numeric' autoFocus={true} underlineColorAndroid="transparent" style={styles.input}
                       onChangeText={(text)=>{this.setState({tixian:text})}}
                      value={this.state.tixian}/>
          </View>
        </View>
        <Text style={{marginTop:pxToDp(50)}}>注：提现金额需5元及以上，不多于余额</Text>
        <Text style={styles.submit} onPress={this._onPress.bind(this)}>提交</Text>
      </ScrollView>
    );
  }
}

var styles = StyleSheet.create({
    contentContainer: {
      paddingVertical: 20,
      alignItems:'center'
    },
    row: {
      flexDirection: 'row',
      alignItems: 'center',
      height:pxToDp(100),
      backgroundColor:'#fff',
      width:pxToDp(640),
      marginBottom:pxToDp(5)
    },
    title: {
      fontWeight: 'bold',
      fontSize:pxToDp(26)
    },
    submit: {
      width: pxToDp(400),
      height: pxToDp(70),
      backgroundColor: DATA.BASE_COLOR,
      color: '#fff',
      textAlign: 'center',
      fontSize: pxToDp(34),
        borderRadius:pxToDp(20),
        paddingTop:pxToDp(20),
      marginTop:pxToDp(100)
    },
    input: {
      width: pxToDp(400),
      fontSize:pxToDp(26)
    },
    all:{
      color:'#36ad50'
    }
  });

const modalStyle = StyleSheet.create({
  modalViewStyle: {
    position: 'absolute',
    top:pxToDp(900),
    alignSelf:'center'
  },
  hudViewStyle: {
    backgroundColor: 'rgba(0,0,0,0.5)',
    paddingLeft:pxToDp(15),
    paddingRight:pxToDp(15),
    paddingTop:pxToDp(10),
    paddingBottom: pxToDp(10),
    borderRadius:pxToDp(10)
  },
  hudTextStyle: {
    color:'#fff'
  }
})
